package com.dendi.controller;

import com.dendi.util.AesException;
import com.dendi.util.WeiChatUtil;
import org.dom4j.DocumentException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


@RestController
public class SetupController {
	
	String token="dendi";
	

	/*Token
	 * zzjava3
	 * 
	 * EncodingAESKey：
	 * 1ZinM8UqAfCv4kFJ7ny5Qns4EzatgH1aJL8EEgilWZZ
	 * 
	 * 接入入微信公众平台（成为了微信公众平台的开发者）
	 * 
	 */
	@RequestMapping(value = "/initWeiChat",method = RequestMethod.GET)
	public String init(HttpServletRequest req){
		String signature=req.getParameter("signature");
		String timestamp=req.getParameter("timestamp");
		String nonce=req.getParameter("nonce");
		String param4=req.getParameter("echostr"); 
		
		System.out.println("initWeiChat timestamp="+timestamp);
		System.out.println("initWeiChat nonce="+nonce);
		System.out.println("initWeiChat signature="+signature);
		System.out.println("initWeiChat echostr="+param4);
		boolean result=false;
		try {
			if(signature.equals(WeiChatUtil.getSHA1(token, timestamp, nonce))){
				result=true;
				
			};
		} catch (AesException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(result){
			return param4;
			
		}else{
			
			return "error";
		}
		
	}
	
	/*
	 * 1. 接收用户给微信公众平台发的消息
	 * 
	 */

	@RequestMapping(value = "/initWeiChat",method = RequestMethod.POST)
	public String message(HttpServletRequest req, HttpServletResponse response) throws IOException, DocumentException{
		System.out.println(req);
		String accessToken=WeiChatUtil.getAccessToken();
		//todo  获取素材列表
		
		InputStream inst=req.getInputStream();
		Map map=WeiChatUtil.xmlToMap(inst);
		System.out.println("FromUserName="+map.get("FromUserName"));
		System.out.println("Content="+map.get("Content"));
		System.out.println("MsgType="+map.get("MsgType"));
		System.out.println("Location_X====="+map.get("Location_X"));
		System.out.println("Location_Y====="+map.get("Location_Y"));
		Map mapres=new HashMap();
		mapres.put("FromUserName", map.get("ToUserName"));
		mapres.put("ToUserName", map.get("FromUserName"));
		mapres.put("Content", "来自公众平台的回复");
		mapres.put("MsgType", "text");   
		mapres.put("CreateTime", 12455744); 
		return WeiChatUtil.MapToXml(mapres);
	}
}

